package src

import (
	"log"
	"net/http"
	"path/filepath"
	"regexp"
	"strings"
)

// 断言接口
type PredicateMatcher interface {
	Match(r *http.Request) bool
}

// 路径断言
type PathPredicate string

// 头部断言
type HeaderPredicate string

// 字符串比较
func (path PathPredicate) Match(request *http.Request) bool {
	if strings.Trim(string(path), " ") == "" {
		return true
	}
	m, err := filepath.Match(string(path), strings.TrimRight(request.URL.Path, "/")+"/")
	if err != nil || !m {
		return false
	}
	return true
}

// 匹配头
func (header HeaderPredicate) Match(request *http.Request) bool {
	headerStr := string(header)
	sHeader := strings.Split(headerStr, ",")
	for _, val := range sHeader {
		rKv := strings.Split(val, ":")
		if len(rKv) != 2 {
			continue
		}
		key := rKv[0]
		patten := rKv[1]
		if value, ok := request.Header[key]; !ok {
			return false
		} else {
			reg, err := regexp.Compile(patten)
			if err != nil { // 正则错误
				log.Fatalln(err)
				return false
			}
			if !reg.MatchString(value[0]) { // header头每个key对应是一个数组，目前就取一个
				return false
			}
		}
	}
	//fmt.Println(sHeader, headerStr)
	//fmt.Println(request.Header)
	return true
}
